<template>
  <div>
    <van-nav-bar title="开始充电" left-arrow left-text="用户"  @click-left="onClickLeft"/>
    <van-cell-group inset class="mt15">
      <div class="pane">
        <div class="left">
          <img src="../assets/car.svg" alt="" v-if="chargingInfo.equipType ===2">
          <img src="../assets/eletrc.svg" alt="" v-else>
        </div>
        <ul class="right">
          <li><label>充电桩编号：</label>{{chargingInfo.equipNo}}</li>
          <li><label>充电桩名称：</label>{{chargingInfo.equipName}}</li>
          <li><label>插座编号：</label>{{chargingInfo.channelNo}}</li>
        </ul>
      </div>
    </van-cell-group>
    <div class="block balance">
      <span>余额：¥{{user.balance}}, 赠送：¥{{user.give}}</span>
      <van-button size="small" plain type="info" to="/recharge">去充值</van-button>
    </div>

    <van-cell-group inset>
      <div class="block">选择充电时长</div>
      <ul class="charge-list">
        <li
          v-for="(item, index) in kxChargeScheme"
          :key="index"
          :class="{active: activeIndex === index}"
          @click="selectChargeTime(item, index)"
        >
          <i>{{item==0?'充满自停':item}}</i> <span v-if="index > 0">小时</span>
        </li>
      </ul>
    </van-cell-group>

    <div v-if="chargeScheme.type == 1">
      <div v-if="time == 0" class="block" style="text-align: center">
        <span style="color: red">电车充满或拔掉插头后自动断电并停止计费</span>
      </div>
      <div v-else class="block">
        <van-switch v-model="chargingFullNotStop" size="16px" /><p/><span style="color: red">开启后，电车充满或拔掉插头后不会自动断电也不会停止计费，直至达到选择时长，如需提前结束，请点击停止充电</span>
      </div>
    </div>
    <div class="block">
      <van-button type="primary" size="large" :disabled="chargingFlag" @click="goCharge"><span v-if="!chargingFlag">开始充电</span><van-loading type="spinner" v-if="chargingFlag" color="#1989fa" >打开插座中</van-loading></van-button>
    </div>
    <div class="mt0" style="text-align: center" v-if="equipScheme && equipScheme.isShowScheme">
      <van-button type="warning" size="mini" @click="isShowScheme = !isShowScheme">计费标准</van-button>
    </div>
    <van-popup
      v-if="equipScheme && equipScheme.isShowScheme"
      v-model="isShowScheme"
      position="bottom"
      :style="{ height: '60%' }"
    >
      <van-nav-bar title="计费方案" right-text="关闭" @click-right="isShowScheme = false"/>
      <div class="block" v-if="chargeScheme">
        <ul class="detail" v-if="chargeScheme.type == 1">
          <li>
            <div class="label-recharge">超出最大功率按度计费价格</div>
            <div class="label-recharge">{{chargeScheme.degreePrice}} 元 / 度</div>
          </li>
          <li
            v-for="(detail, i) in parseDetail(chargeScheme.schemeDetailed)"
            :key="i"
            size="large"
          >
            <div class="label-recharge">功率：{{detail.min_power}} - {{detail.max_power}} 瓦</div>
            <div class="label-recharge">单价：{{detail.ele_price}} 元 / 小时</div>
          </li>
        </ul>
        <ul class="detail" v-else-if="chargeScheme.type == 2">
          <li>
            <div class="label-recharge">不在时间段按平电费价格</div>
            <div class="label-recharge">尖电费费率/服务费:{{parseDetail(chargeScheme.schemeDetailed).topCost}}/{{parseDetail(chargeScheme.schemeDetailed).topFees}}</div>
            <div class="label-recharge">峰电费费率/服务费:{{parseDetail(chargeScheme.schemeDetailed).peakCost}}/{{parseDetail(chargeScheme.schemeDetailed).peakFees}}</div>
            <div class="label-recharge">平电费费率/服务费:{{parseDetail(chargeScheme.schemeDetailed).flatCost}}/{{parseDetail(chargeScheme.schemeDetailed).flatFees}}</div>
            <div class="label-recharge">谷电费费率/服务费:{{parseDetail(chargeScheme.schemeDetailed).lowCost}}/{{parseDetail(chargeScheme.schemeDetailed).lowFees}}</div>
<!--            <div class="label-recharge">{{chargeScheme.degreePrice}} 元 / 度</div>-->
          </li>
          <li
            v-for="(detail, i) in parseDetail(chargeScheme.schemeDetailed).detailed"
            :key="i"
            size="large"
          >
            <div class="label-recharge">时间：{{detail.start_time}} - {{detail.end_time}}</div>
            <div class="label-recharge">单价：{{detail.ele_price}} 元 / 度</div>
          </li>
        </ul>
      </div>
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'GeCharge',
  data () {
    return {
      chargingFlag: false,
      chargingInfo: {},
      kxChargeScheme: [0, 1, 2, 3, 4, 6, 8, 10],
      activeIndex: 0,
      time: 0,
      chargingFullNotStop: false,
      isShowScheme: false,
      showCover: false
    }
  },
  computed: {
    user () {
      return this.$store.state.user || {}
    },
    chargeScheme () {
      return this.chargingInfo.kxChargeScheme
    },
    equipScheme () {
      return this.chargingInfo.kxEquipScheme
    }
  },
  methods: {
    onClickLeft () {
      this.$router.push('/')
    },
    initChargingInfo (equipNo, channelNo) {
      sessionStorage.removeItem('equipNo')
      sessionStorage.removeItem('channelNo')
      this.$http.get('/getStartChargingEquipInfo', {
        params: {
          equipNo: equipNo,
          channelNo: channelNo
        }
      }).then(res => {
        if (res.code === 200) {
          this.chargingInfo = res.data
          // 一户多冲不再处理充电中情况
          // if (this.chargingInfo.chargingStatus === 1) {
          //   setTimeout(() => {
          //     this.$router.push(`/charging?equipId=${this.chargingInfo.equipId}&channelNo=${this.chargingInfo.channelNo}`)
          //   }, 500)
          // }
        }
      })
    },
    selectChargeTime (item, index) {
      this.activeIndex = index
      this.time = item
    },
    goCharge () {
      this.chargeAction()
    },
    chargeAction () {
      if (this.chargingFlag) return
      this.chargingFlag = true
      const data = {
        equipNo: this.chargingInfo.equipNo,
        channelNo: this.chargingInfo.channelNo,
        planChargingTime: this.time,
        chargingFullNotStop: this.chargingFullNotStop ? 1 : 0
      }
      this.$http.post('/system/equip/openChannelByTime', this.$qs.stringify(data), {
        timeout: 60000
      }).then(res => {
        this.chargingFlag = false
        if (res.code === 200) {
          this.$router.push(`/charging?equipId=${this.chargingInfo.equipId}&channelNo=${this.chargingInfo.channelNo}`)
        } else {
          this.$toast.fail(res.msg)
        }
      }).catch(() => {
        this.chargingFlag = false
        this.$toast.fail('网络超时')
      })
    },
    parseDetail (detail = '[]') {
      try {
        return JSON.parse(detail) || []
      } catch (err) {
        console.error(err)
        return []
      }
    }
  },
  created () {
    if (sessionStorage.getItem('equipNo') && sessionStorage.getItem('channelNo')) {
      this.initChargingInfo(sessionStorage.getItem('equipNo'), sessionStorage.getItem('channelNo'))
    } else if (sessionStorage.getItem('equipNo') && !sessionStorage.getItem('channelNo')) {
      this.$router.push('/commonly')
    } else {
      this.$dialog.confirm({
        title: '请求失败',
        message: '获取信息失败！请重新扫描设备二维码',
        confirmButtonText: '重新扫描',
        cancelButtonText: '返回',
        closeOnPopstate: false
      }).then(() => {
        this.$store.dispatch('getScan')
        this.$router.push('/')
      }).catch(() => {
        this.$router.push('/')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.pane {
  padding: 15px;
  display: flex;  align-items: center;
  .left {
    padding-right: 15px;
    img {
      width: 60px;
    }
  }
  .right {
    line-height: 24px;
  }
}
.balance {
  display: flex; align-items: center; justify-content: space-between;
}
.charge-list {
  display: flex; flex-wrap: wrap; justify-content: space-between;
  padding: 15px; padding-top: 0;
  li {
    box-sizing: border-box;
    width: 24%;
    padding: 5px 5px; margin: 5px 0;
    border: solid 1px #ddd; border-radius: 4px;
    line-height: 18px; text-align: center;
    &.active {
      border: solid 1px #08e;
      box-shadow: 0 0 2px rgba(#08e, 1) inset;
    }
    & > span {
      font-size: 10px;
    }
    & > i {
      color: #09f; font-weight: bold; font-size: 12px;
    }
    .give {
      display: block;
      font-size: 12px; color: #f60;
    }
  }
}
.detail {
  border: solid 1px #f0f0f0; border-radius: 5px;
  padding: 0px 10px;
  li {
    display: flex; align-items: center; flex-wrap: wrap;
    border-bottom: solid 1px #f5f5f5;
    padding: 5px 0;
    line-height: 28px;
    &:last-child {
      border: none
    }
    .label-recharge {
      width: 50%;
      font-size: 13px;
    }
  }
}
</style>
